import Koa from 'koa';
import KoaRouter from '@koa/router';
import koaBodyParser from 'koa-bodyparser';
import koaCors from '@koa/cors';
import dayjs from 'dayjs';
import dayjsUtc from 'dayjs/plugin/utc';
import dayjsTimezone from 'dayjs/plugin/timezone';
import dayjsAdvancedFormat from 'dayjs/plugin/advancedFormat';

import { registerConfigApi } from './services/config/index';
import { registerProxies } from './services/proxy/index';
import { registerCasService } from './services/cas';
import Logger from './utils/Logger';
import traceHelper, { traceHeaderKey } from './middleware/traceHelper';
import accessLogHelper from './middleware/accessLogHelper';
import standaloneOssVerify from './middleware/standaloneSsoVerify';
import config from './config';

dayjs.extend(dayjsUtc);
dayjs.extend(dayjsTimezone);
dayjs.extend(dayjsAdvancedFormat);

const app = new Koa();
const router = new KoaRouter();

// TODO: 公有云环境下接入 IT CAS
const runApp = () => {
  app.on('error', (error) => {
    Logger.error('Global uncaught exception', error);
  });

  app.use(traceHelper);
  app.use(accessLogHelper);
  app.use(koaCors({
    credentials: true,
    exposeHeaders: [
      'token', // 用于 standaloneSsoVerify.ts refreshedToken
      traceHeaderKey,
    ],
  }));
  config.isEnv3rdPlatform() && app.use(standaloneOssVerify);
  config.isEnvPublicPlatform() && registerCasService(app, router);
  // koa-proxies 需要在 koa-bodyparser 之前注册才能正常工作
  // https://github.com/vagusX/koa-proxies#attention
  registerProxies(app);
  app.use(koaBodyParser());
  registerConfigApi(router);
  app.use(router.routes());

  const listenPort = process.env.PORT || 4000;
  app.listen({ port: listenPort, host: '0.0.0.0' }, () => {
    // eslint-disable-next-line no-console
    console.log(`Listening on port ${listenPort}, process id: ${process.pid}`);
  });
};

runApp();
